package com.zhuoyian.dl.control;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.zhuoyian.dl.service.DownloadPresent;
import com.zhuoyian.dl.util.ConnUtil;
import com.zhuoyian.dl.util.DownloadLog;
import com.zhuoyian.dl.util.DownloadThreadFactory;

/**
 * 并行下载
 * @author Administrator
 *
 */
public class ParallelDownload  extends DownloadControl{
	private static DownloadControl serialDL;

	/**
	 * ���ʵ��
	 */
	public static DownloadControl getInstance() {
		if (serialDL == null) {
			synchronized (ParallelDownload.class) {
				if (serialDL == null) {
					serialDL = new ParallelDownload();
				}
			}
		}
		return serialDL;
	}

	/**
	 */
	private ParallelDownload() {
		super();
	}

	/**
	 */
	@Override
	public int start(final DownloadPresent dlPresent) {
		super.start(dlPresent);
		DownloadThreadFactory.THREAD.submit(new Runnable() {

			@Override
			public void run() {
				executeTask(dlPresent);
			}
		});
		return dlPresent.getTaskId();
	}

	private void executeTask(DownloadPresent dlPresent) {
		URL url = null;
		try {
			url = new URL(dlPresent.getDlFile().getUrl());
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		}
		if (url == null) {
			return;
		}
		HttpURLConnection conn = ConnUtil.connect(url);
		if (conn == null) {
			DownloadLog.print("connection time out");
			return;
		}
		int size = conn.getContentLength();
		conn.disconnect();
		conn = null;
		dlPresent.setFileSize(size);
		dlPresent.download(url);
	}

}
